package com.client.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.client.pojo.Users;
import com.client.service.UsersService;
import com.client.utils.JwtUtils;
import com.client.utils.RedisUtils;
import com.client.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 平台用户信息表 前端控制器
 * </p>
 *
 * @author ckick
 * @since 2025-09-20 08:28:54
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    UsersService usersService;
    @Autowired
    RedisUtils redisUtils;

    /**
     * 查询用户基本信息
     *
     * @param userId 用户ID
     * @return 用户基本信息的json格式
     */
    @GetMapping("getUsers/{userId}")
    public ResponseMsg getUsers(@PathVariable Integer userId) {
        if (userId == null || userId <= 0) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "用户ID不合法，请提供有效的用户ID");
        }
        try {
            Users user = usersService.getById(userId);
            if (user == null) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "用户信息为空!");
            }
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                    "查询用户基本信息", usersService.getById(userId));
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "查询用户失败.");
        }
    }

    /**
     * 修改用户信息
     *
     * @param user 用户实体
     * @return 返回修改结果
     */
    @PostMapping("updateUsers")
    public ResponseMsg updateUsers(@RequestBody Users user) {
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改完成", usersService.updateById(user));
    }

    @RequestMapping("login")
    ResponseMsg login(@RequestBody Users users) {
        String phone = users.getPhone();
        String pwd = users.getEncryptedPassword();
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        Users ret = usersService.getOne(wrapper);
        if (ret == null) {
            return ResponseMsg.getInstance(-201, "该账号还没有注册");
        }
        System.out.println("salt============" + ret.getSalt());
        pwd = DigestUtils.md5DigestAsHex((pwd + ret.getSalt()).getBytes(StandardCharsets.UTF_8));
        System.out.println("pwd===========" + pwd);
        for (int i = 0; i < ret.getSaltCount(); i++) {
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        }
        System.out.println("pwd===========" + pwd);
        if (pwd.equals(ret.getEncryptedPassword())) {
            String token = JwtUtils.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(ret), 3600 * 240000);
            redisUtils.set("token" + phone, token);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "登入成功", token, ret);
        }
        return ResponseMsg.getInstance(ResponseMsg.ERROR, "密码错误");
    }

    @RequestMapping("userAdd")
    ResponseMsg userAdd(@RequestBody Users user) {
        // 验证必填字段
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "用户名不能为空");
        }

        if (user.getPhone() == null || user.getPhone().trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "手机号不能为空");
        }

        if (user.getEncryptedPassword() == null || user.getEncryptedPassword().trim().isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "密码不能为空");
        }

        // 检查手机号是否已存在
        QueryWrapper<Users> phoneCheck = new QueryWrapper<>();
        phoneCheck.eq("phone", user.getPhone());
        if (usersService.getOne(phoneCheck) != null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "该手机号已被注册");
        }

        // 如果email为空，设置为null而不是空字符串
        if (user.getEmail() != null && user.getEmail().trim().isEmpty()) {
            user.setEmail(null);
        }

        // 如果email不为空，检查是否已存在
        if (user.getEmail() != null) {
            QueryWrapper<Users> emailCheck = new QueryWrapper<>();
            emailCheck.eq("email", user.getEmail());
            if (usersService.getOne(emailCheck) != null) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "该邮箱已被注册");
            }
        }

        System.out.println("name=============" + user.getUsername());
        Random random = new Random();
        //随机盐
        String salt = generateRandomString(random.nextInt(10) + 6);
        //随机散列次数
        int times = random.nextInt(1024) + 10;
        //第一次加密
        String pwd = DigestUtils.md5DigestAsHex((user.getEncryptedPassword() + salt).getBytes(StandardCharsets.UTF_8));
        //多次加密
        for (int i = 0; i < times; i++) {
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        }
        user.setEncryptedPassword(pwd);
        user.setSalt(salt);
        user.setSaltCount(times);
        //设置创建时间
        user.setCreatedAt(new Date());
        usersService.save(user);
        return ResponseMsg.success();
    }

    private String generateRandomString(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须大于0");
        }
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            // 生成 0-25 的随机数，加上 'a' 的 ASCII 值，得到 a-z 之间的字符
            char randomChar = (char) ('a' + random.nextInt(26));
            sb.append(randomChar);
        }
        return sb.toString();
    }

    @GetMapping("updateEmail/{userId}/{email}")
    public ResponseMsg updateEmail(@PathVariable Integer userId, @PathVariable String email) {
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改完成", usersService.updateEmail(userId, email));
    }

    @GetMapping("changePassword/{oldPassword}/{newPassword}/{userId}")
    public ResponseMsg changePassword(@PathVariable String oldPassword,
                                      @PathVariable String newPassword,
                                      @PathVariable Integer userId) {
        Users user = usersService.getById(userId);
        String salt = user.getSalt();
        String password = user.getEncryptedPassword();
        int saltCount = user.getSaltCount();
        //第一次加盐
        String pwd = DigestUtils.md5DigestAsHex((oldPassword + salt).getBytes(StandardCharsets.UTF_8));
        for (int i = 0; i < saltCount; i++) {
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        }
        System.out.println("加盐============"+salt);
        System.out.println("加盐次数============"+saltCount);
        System.out.println("NEWpwd===========" + pwd);
        System.out.println("OIDpwd===========" + password);
        if (!pwd.equals(password)) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "原密码错误");
        } else {
            //设置新密码
            newPassword = DigestUtils.md5DigestAsHex((newPassword + salt).getBytes(StandardCharsets.UTF_8));
            for (int i = 0; i < saltCount; i++) {
                newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes(StandardCharsets.UTF_8));
            }
            usersService.setNewPassword(userId, newPassword);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改密码成功");
        }
    }

    @GetMapping("deleteNowUser/{phone}")
    public ResponseMsg deleteNowUser(@PathVariable String phone) {
        redisUtils.del("token" + phone);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "删除成功");
    }

    /**
     * 获取所有用户
     * @param page 页码
     * @param limit 每页数量
     * @return ResponseMsg
     */
    @GetMapping("getAllUsers/{page}/{limit}")
    public ResponseMsg getAllUsers(@PathVariable Integer page,
                                   @PathVariable Integer limit) {
        IPage<Users> p = new Page<>(page, limit);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "分页查询用户数据", usersService.page(p));
    }
    @RequestMapping("resetPwd")
    ResponseMsg resetPwd(@RequestParam String email,@RequestParam String pwd){
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        Users user = usersService.getOne(wrapper);
        Random random = new Random();
        //随机盐
        String salt = generateRandomString(random.nextInt(10) + 6);
        //随机散列次数
        int times = random.nextInt(1024) + 10;
        //第一次加密
         pwd = DigestUtils.md5DigestAsHex((pwd + salt).getBytes(StandardCharsets.UTF_8));
        //多次加密
        for (int i = 0; i < times; i++) {
            pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        }
        user.setEncryptedPassword(pwd);
        user.setSalt(salt);
        user.setSaltCount(times);
        usersService.update(user,wrapper);
        return ResponseMsg.getInstance(200,"密码重置成功");
    }
}
